package chess

import (
	"../conf"
	"encoding/json"
	"github.com/gorilla/websocket"
)

type Player struct {
	action     uint8 //1 落 2 吃 3 走
	pieces     uint8
	color      uint8
	id         uint32
	connection *websocket.Conn
}

func (p Player) PlayerId() uint32 {
	return p.id
}

func (p *Player) SendMessage(message interface{}) {
	content, err := json.Marshal(message)
	if err != nil {
		conf.Logger.Error("Json encode error, %s", err)
		return
	}
	ws, err := p.connection.NextWriter(websocket.TextMessage)
	if err != nil {
		conf.Logger.Error("Get writer error, %s", err)
		return
	}
	_, err = ws.Write(content)
	if nil != err {
		conf.Logger.Error("Send message error. %s", err)
	}
}

func (p *Player) SendString(message string) {
	ws, err := p.connection.NextWriter(websocket.TextMessage)
	if err != nil {
		conf.Logger.Error("Get writer error, %s", err)
		return
	}
	_, err = ws.Write([]byte(message))
	if nil != err {
		conf.Logger.Error("Send message error. %s", err)
	}
}

func (p *Player) ReadMessage(message interface{}) {
	err := p.connection.ReadJSON(message)
	if err != nil {
		p.connection.ReadMessage()
		conf.Logger.Error(err)
	}
}

func (p *Player) PieceColor(c uint8) {
	p.color = c
}

func (p *Player) TakePiece() *Piece {
	p.pieces = p.pieces - 1
	return &Piece{p.color}
}
